package com.yusp75.myexam.com.yusp75.myexam.data

import com.yusp75.myexam.com.yusp75.myexam.di.StateFlowManager
import com.yusp75.myexam.data.Book
import com.yusp75.myexam.data.BookDao
import com.yusp75.myexam.data.BookWithCounts
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class BookRepository(
    private val bookDao: BookDao,
    private val flowManager: StateFlowManager = StateFlowManager()
) {
    val allBooks: Flow<List<BookWithCounts>> = bookDao.getAllBooks()

    suspend fun deleteBook(book: Book) {
        withContext(Dispatchers.IO) {
            bookDao.deleteQuestionsByBookId(book.id)
            bookDao.delete(book)
        }
    }

    // 书选择
    suspend fun selectBook(currentBookId: Int, book: Book) {
        bookDao.updateBookSelection(currentBookId, false)
        bookDao.updateBookSelection(book.id, true)
    }

    // 在Repository层转换Flow为StateFlow：
    val selectedBook: StateFlow<Book?>
        get() = bookDao.getSelectedBook()
            .catch { emit(null) } // 捕获所有异常转为null
            .stateIn(
                scope = flowManager.scope,
                started = SharingStarted.WhileSubscribed(5000),
                initialValue = null
            )


    fun clear() {
        flowManager.destroy() // 暴露清理接口
    }
}
